<template>
  <div style="margin-left: 15px">
    <div
        style="position: fixed; z-index: 10; flex-direction: column; background: white; width: 100%; margin-top: -10px">
      <h1 class="header-text">管理员信息管理</h1>

      <div class="search-bar">
        <el-input v-model="searchQuery" placeholder="输入ID/姓名 搜索管理员" @input="handleInput"></el-input>
      </div>

      <div style="float:left;">
        <el-button type="primary" @click="handleAdd">新增管理员
          <el-icon style="margin-left: 10px;">
            <CirclePlusFilled/>
          </el-icon>
        </el-button>
        <el-button :disabled="!multipleSelection.length" type="danger" @click="handleBatchDelete">批量删除
          <el-icon style="margin-left: 10px;">
            <RemoveFilled/>
          </el-icon>
        </el-button>
      </div>

      <div style="float: right; margin-right: 100px">
        <el-pagination :current-page="currentPage"
                       :page-size="pageSize"
                       :page-sizes="[10, 20, 50, 100]"
                       :total="totalCount"
                       layout="total, sizes, prev, pager, next, jumper"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </div>

    <div class="table-container" style="margin-top: 10%;">
      <el-table :data="paginatedAdmins" style="width: 100%" @selection-change="handleSelectionChange"
                @row-click="handleRowClick">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="ID" prop="aid" style="width: 20%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.aid)"></span>
          </template>
        </el-table-column>
        <el-table-column label="姓名" prop="aname" style="width: 20%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.aname)"></span>
          </template>
        </el-table-column>
        <el-table-column label="密码" prop="psw" style="width: 20%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.psw)"></span>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" prop="create_time" style="width: 20%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.create_time)"></span>
          </template>
        </el-table-column>
        <el-table-column label="更新日期" prop="update_time" style="width: 20%">
          <template #default="scope">
            <span v-html="highlightMatch(scope.row.update_time)"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="danger" @click.stop="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 管理员信息模态框 -->
    <el-dialog :model-value="dialogVisible" title="管理员信息" @close="dialogVisible = false">
      <el-form :model="selectedAdmin">
        <el-form-item label="ID">
          <el-input v-model="selectedAdmin.aid" :class="{'is-error': aidExistError}" :disabled="isEdit"
                    autocomplete="off" @input="checkAid"></el-input>
          <span v-if="aidExistError" class="error-message">该ID已使用，请重新输入！</span>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="selectedAdmin.aname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="selectedAdmin.psw" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="创建日期">
          <el-input v-model="selectedAdmin.create_time" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="更新日期">
          <el-input v-model="selectedAdmin.update_time" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-if="!showButton" type="primary" @click="handleConfirm">确认修改</el-button>
        <el-button v-if="showButton" type="primary" @click="addConfirm">确认添加</el-button>
      </template>
    </el-dialog>
  </div>
  <br class="fixed-container highlight">
</template>

<script>
import {ElMessage} from "element-plus";
import {CirclePlusFilled, RemoveFilled} from "@element-plus/icons-vue";
import AdminAxiosService from "@/service/AdminAPI.js"


export default {
  components: {
    RemoveFilled,
    CirclePlusFilled
  },
  data() {
    return {
      searchQuery      : '',
      paginatedAdmins  : [],
      Admins           : [], // 存储所有管理员数据
      AdminsAid        : [], // 存储ID数组
      showButton       : false,
      dialogVisible    : false,
      selectedAdmin    : {
        aid        : '',
        aname      : '',
        psw        : '',
        create_time: '',
        update_time: '',
      },
      multipleSelection: [],
      aidExistError    : false, // ID已存在错误状态
      isEdit           : false, // 是否处于编辑模式
      originalAid      : '', // 原始ID，用于编辑时检查是否修改了ID
      currentPage      : 1, // 当前页码
      pageSize         : 10, // 每页显示条数
      totalCount       : 0, // 总条数
      size             : 'large', // 分页组件大小
    };
  },
  computed: {
    paginatedAdmins() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.Admins.slice(start, end); // 返回分页后的管理员数据
    }
  },
  methods : {
    handleInput() {
      this.paginatedAdmins = this.Admins.filter(admin => {
        const searchString = `${admin.aname} ${admin.aid} ${admin.mobile}`;
        return searchString.includes(this.searchQuery);
      }); // 更新分页后的管理员数据
    },
    highlightMatch(text) {
      if (!this.searchQuery) return text;
      const regex = new RegExp(this.escapeRegExp(this.searchQuery), 'gi');
      return text.replace(regex, match => `<span style="color: #ff00f3;font-weight: bolder">${match}</span>`);
    },
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    },
    async handleDelete(index, row) {
      try {
        await AdminAxiosService.deleteAdmin(row.aid); // 调用 API 删除管理员
        this.Admins.splice(index, 1); // 从管理员列表中删除
        this.totalCount--; // 更新总条数
        this.$message({
          type   : 'success',
          message: '管理员信息删除成功!'
        });
        await this.fetchAdmins(); // 重新获取管理员列表
      } catch (error) {
        console.error('Error deleting admin:', error);
        this.$message({
          type   : 'error',
          message: '删除管理员信息失败，请重试!'
        });
      }
    },
    async handleBatchDelete() {
      try {
        const deletePromises = this.multipleSelection.map(admin => AdminAxiosService.deleteAdmin(admin.aid));
        await Promise.all(deletePromises);
        this.Admins = this.Admins.filter(admin => !this.multipleSelection.includes(admin)); // 更新管理员列表
        this.totalCount -= this.multipleSelection.length; // 更新总条数
        this.multipleSelection = []; // 清空选中
        this.$message({
          type   : 'success',
          message: '批量删除成功!'
        });
        await this.fetchAdmins(); // 重新获取管理员列表
      } catch (error) {
        console.error('Error batch deleting admins:', error);
        this.$message({
          type   : 'error',
          message: '批量删除失败，请重试!'
        });
      }
    },
    handleAdd() {
      this.showButton = true;
      this.isEdit = false;
      this.aidExistError = false;
      this.selectedAdmin = {
        aid        : '',
        aname      : '',
        psw        : '',
        create_time: '',
        update_time: ''
      };
      this.dialogVisible = true; // 显示模态框
    },
    handleRowClick(row) {
      this.isEdit = true;
      this.originalAid = row.aid;
      this.selectedAdmin = {...row}; // 深拷贝管理员数据
      this.dialogVisible = true; // 显示模态框
    },
    async handleConfirm() {
      try {
        await AdminAxiosService.updateAdmin(this.selectedAdmin.aid, this.selectedAdmin); // 更新管理员信息
        this.$message({
          type   : 'success',
          message: '管理员信息更新成功!'
        });
        this.dialogVisible = false; // 关闭模态框
        await this.fetchAdmins(); // 重新获取管理员列表
      } catch (error) {
        this.$message({
          type   : 'error',
          message: '更新管理员信息失败，请重试!'
        });
      }
    },
    async addConfirm() {
      if (!this.selectedAdmin.aid) {
        ElMessage.error("请输入ID！");
        return;
      }
      this.showButton = false;
      try {
        await AdminAxiosService.addAdmin(this.selectedAdmin); // 添加新管理员
        this.$message({
          type   : 'success',
          message: '管理员信息添加成功!'
        });
        this.dialogVisible = false; // 关闭模态框
        await this.fetchAdmins(); // 重新获取管理员列表
      } catch (error) {
        this.$message({
          type   : 'error',
          message: '添加管理员失败，请重试!'
        });
      }
    },
    async fetchAdmins() {
      try {
        const data = await AdminAxiosService.fetchAllAdmins(); // 获取所有管理员数据、
        console.log(data)
        this.Admins = data; // 更新管理员列表
        this.totalCount = data.length; // 更新总条数
        this.paginatedAdmins = [...this.Admins]; // 初始化分页管理员
        this.AdminsAid = this.Admins.map(admin => admin.aid); // 存储所有管理员ID
      } catch (error) {
        console.error('Error fetching admins:', error);
      }
    },
    handleSizeChange(size) {
      this.pageSize = size; // 更新每页显示条数
      this.currentPage = 1; // 重置为第一页
    },
    handleCurrentChange(page) {
      this.currentPage = page; // 更新当前页码
    },
    async checkAid() {
      this.aidExistError = this.AdminsAid.includes(this.selectedAdmin.aid) && this.originalAid !== this.selectedAdmin.aid; // 检查ID是否已存在
    },
    handleSelectionChange(val) {
      this.multipleSelection = val; // 更新选中的管理员
    }
  },

  async created() {
    await this.fetchAdmins(); // 组件创建时获取管理员列表
  }
};
</script>

<style scoped>
.fixed-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 999;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.error-message {
  color: red;
  font-size: 12px;
}

.highlight {
  color: red;
}

.search-bar {
  width: 95%;
  margin-bottom: 20px;
}

.header-text {
  background-clip: padding-box;
  display: flex;
  flex-direction: column;
  float: left;
  background: -webkit-linear-gradient(315deg, #3f9dfd 15%, #f36b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
  font-weight: bolder;
}
</style>
